import { addApp, apiInterceptors, getAppList, getTeamMode, updateApp } from '@/client/api';
import { CreateAppParams } from '@/types/app';
import { useRequest } from 'ahooks';
import { App, ConfigProvider, Divider, Form, Input, Modal, Spin,TreeSelect } from 'antd';
import classNames from 'classnames';
import Image from 'next/image';
import { useRouter } from 'next/router';
import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import styles from '@/pages/construct/app/components/create-app-modal/styles.module.css'


const CreateRoleModal: React.FC<{
  open: boolean;
  onCancel: () => void;
  refresh?: any;
  type?: 'add' | 'edit';
}> = ({ open, onCancel, type = 'add', refresh }) => {
  const { t, i18n } = useTranslation();
  const roleInfo = JSON.parse(localStorage.getItem('new_role_info') || '{}');
  const { message } = App.useApp();
  const [form] = Form.useForm();

  const [treeValue, setTreeValue] = useState();
  const treeData = [
    {
      title: '智能对话',
      value: '0-0',
      key: '0-0'
    },
    {
      title: '应用管理',
      value: '0-1',
      key: '0-1',
      children: [
        {
          title: '应用程序',
          value: '0-1-0',
          key: '0-1-0',
        },
        {
          title: '工作流',
          value: '0-1-1',
          key: '0-1-1',
        },
        {
          title: '模型管理',
          value: '0-1-2',
          key: '0-1-2',
        },
        {
          title: '数据库',
          value: '0-1-3',
          key: '0-1-3',
        },
        {
          title: '知识库',
          value: '0-1-4',
          key: '0-1-4',
        },
        {
          title: '提示词',
          value: '0-1-5',
          key: '0-1-5',
        },
        {
          title: 'Noah.Graph',
          value: '0-1-6',
          key: '0-1-6',
        },
        {
          title: '关于Noah.X',
          value: '0-1-7',
          key: '0-1-7',
        }
      ],
    },
    {
      title: '应用广场',
      value: '0-2',
      key:'0-2'
    },
    {
      title: '系统管理',
      value: '0-3',
      key:'0-3',
      children:[
        {
          title: '用户',
          value: '0-3-1',
          key:'0-3-1'
        },
        {
          title: '角色',
          value: '0-3-2',
          key:'0-3-2'
        },
        {
          title: '权限',
          value: '0-3-3',
          key:'0-3-3'
        }
      ]
    },
  ];

  const onChange = (newValue: string[]) => {
    console.log('onChange ', newValue);
    setTreeValue(newValue);
  };

  const tProps = {
    treeData,
    treeValue,
    onChange,
    treeCheckable: true,
    showCheckedStrategy: true,
    treeDefaultExpandAll:true,
    placeholder: '',
    style: {
      width: '100%',
    },
  };

  const router = useRouter();
  const language = i18n.language === 'en';

  // 获取工作模式列表
  const { data, loading } = useRequest(async () => {
    const [_, res] = await apiInterceptors(getTeamMode());
    return res ?? [];
  });

  // 创建应用
  const { run: createRole, loading: createLoading } = useRequest(
    async (params: CreateAppParams) => {
      if (type === 'edit') {
        return await apiInterceptors(
          updateApp({
            role_code: roleInfo?.role_code,
            language: 'zh',
            ...params,
          }),
        );
      } else {
        return await apiInterceptors(
          addApp({
            language: 'zh',
            ...params,
          }),
        );
      }
    },
    {
      manual: true,
      onSuccess: async res => {
        const [error, data] = res;
        if (!error) {
          if (type === 'edit') {
            const [, res] = await apiInterceptors(getAppList({}));
            const curApp = res?.role_list?.find(item => item.role_code === roleInfo?.role_code);
            localStorage.setItem('new_role_info', JSON.stringify({ ...curApp, isEdit: true }));
            message.success(t('Update_successfully'));
          } else {
            message.success(t('Create_successfully'));
            localStorage.setItem('new_role_info', JSON.stringify(data));
          }
        } else {
          message.error(type === 'edit' ? t('Update_failure') : t('Create_failure'));
        }
        await refresh?.();
        onCancel();
      },
    },
  );

  const mode = useMemo(() => {
    return data?.filter(item => item.value === roleInfo?.team_mode)?.[0];
  }, [roleInfo, data]);

  if (loading) {
    return null;
  }

  return (
    <ConfigProvider
      theme={{
        components: {
          Button: {
            defaultBorderColor: '#d9d9d9',
          },
        },
      }}
    >
      <Modal
        className={styles['create-app-modal-container']}
        title={t('create_role')}
        width={900}
        open={open}
        onOk={async () => {
          form.validateFields().then(async (values: any) => {
            await createRole({
              role_name: values?.role_name,
              role_describe: values?.role_describe,
              menu_auth: values?.menu_auth?.value,
            });
          });
        }}
        onCancel={onCancel}
        centered={true}
      >
        <Spin spinning={createLoading}>
          <div className='flex flex-1'>
            <Form
              layout='vertical'
              className='w-full'
              form={form}
              initialValues={{
                menu_auth: mode || data?.[0],
                role_name: roleInfo?.role_name,
                role_describe: roleInfo?.role_describe,
              }}
            >
             <Form.Item
                label={`${t('role_id')}：`}
                name='role_id'
              >
                <Input autoComplete='off' className='h-8' />
              </Form.Item>
              <Form.Item
                label={`${t('role_name')}：`}
                name='role_name'
                required
                rules={[{ required: true, message: t('input_role_text') }]}
              >
                <Input placeholder={t('input_role_text')} autoComplete='off' className='h-8' />
              </Form.Item>
              <Form.Item
                label={`${t('Description')}：`}
                name='role_describe'
                required
                rules={[
                  {
                    required: true,
                    message: t('Please_input_the_description'),
                  },
                ]}
              >
                <Input.TextArea
                  autoComplete='off'
                  placeholder={t('Please_input_the_description')}
                  autoSize={{ minRows: 2.5 }}
                />
              </Form.Item>
              <Form.Item 
                label={`${t('menu_auth')}：`}
                required
                rules={[{ required: true, message: t('please_select_auth') }]}
              >
                <TreeSelect {...tProps} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}  />
              </Form.Item>
            </Form>
          </div>
        </Spin>
      </Modal>
    </ConfigProvider>
  );
};

export default CreateRoleModal;
